﻿using Abp;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using FwProject.Product.Dto;
using FwProject.ShopApplication;
using FwProject.ShoppingMall.Product;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FwProject.Product
{
    public class ProductTypeAttrAppService : FwProjectAppServiceBase, IProductTypeAttrAppService
    {
        private readonly IRepository<ProductType_Attr, Guid> _repositoryProductTypeAttr;
        private IGuidGenerator _guid { get; set; }
        private IObjectMapper _map { get; set; }

        public ProductTypeAttrAppService(IRepository<ProductType_Attr, Guid> repositoryProductTypeAttr)
        {
            _repositoryProductTypeAttr = repositoryProductTypeAttr;
            _guid = SequentialGuidGenerator.Instance;
        }

        public async Task UpdatedBatchAsync(Guid id, ProductTypeAttrEnterDto input)
        {
            //获取原来的类型属性数据
            var original = await _repositoryProductTypeAttr.GetAll().Where(o => o.ProductTypeid == id).ToListAsync();
            var newids = input.ProductTypeAttrInputs;
            if (original.Count > 0)
            {
                //获取要删除的数据
                var removes = original.Where(o => newids.Any(s => s.Id == o.Id) == false).ToList();
                if (removes?.Count > 0)//判断是否有删除
                    for (int i = 0; i < removes.Count; i++)//执行删除操作
                        await _repositoryProductTypeAttr.DeleteAsync(removes[i]);
            }
            //获取要新增的数据
            var adds = newids.Where(r => original.Any(o => o.Id == r.Id) == false);
            foreach (var a in adds)
            {
                a.ProductTypeid = id;
                ProductType_Attr attr =a.MapTo<ProductType_Attr>();
                attr.Id = _guid.Create();
                //新增操作
                await _repositoryProductTypeAttr.InsertAsync(attr);
            }
        }

        public async Task<ProductTypeAttrEnterDto> GetEnterDtoAsync(Guid id)
        {
            var list = await _repositoryProductTypeAttr.GetAll().Where(o => o.ProductTypeid == id).ToListAsync();
            
            ProductTypeAttrEnterDto dto = new ProductTypeAttrEnterDto();
            dto.ProductTypeAttrInputs = list.MapTo<List<ProductTypeAttrInput>>();
            return dto;
        }
    }
}
